<template>
  <view class="answer-page">
    <view v-if="loading" class="loading">
      <text>加载中...</text>
    </view>

    <view v-else class="question-container">
      <view class="question-header">
        <text class="question-title">{{ question.questionTitle }}</text>
        <text class="question-type">{{ getQuestionTypeLabel(question.questionType) }}</text>
      </view>

      <!-- 单选题 -->
      <view v-if="question.questionType === '1'" class="options-list">
        <view v-for="option in options"
              :key="option.optionId"
              class="option-item"
              :class="{
                'selected': selectedAnswer === option.optionId,
                'disabled': showResult
              }"
              @tap="!showResult && selectAnswer(option.optionId)">
          <text class="option-label">{{ option.optionId }}.</text>
          <text class="option-content">{{ option.optionContent }}</text>
        </view>
      </view>

      <!-- 多选题 -->
      <view v-else-if="question.questionType === '2'" class="options-list">
        <view v-for="option in options"
              :key="option.optionId"
              class="option-item"
              :class="{
                'selected': selectedAnswers.includes(option.optionId),
                'disabled': showResult
              }"
              @tap="!showResult && selectMultiAnswer(option.optionId)">
          <text class="option-label">{{ option.optionId }}.</text>
          <text class="option-content">{{ option.optionContent }}</text>
        </view>
      </view>

      <!-- 判断题 -->
      <view v-else-if="question.questionType === '3'" class="options-list">
        <view class="option-item"
              :class="{
                'selected': selectedAnswer === 'true',
                'disabled': showResult
              }"
              @tap="!showResult && selectAnswer('true')">
          <text class="option-label">A.</text>
          <text class="option-content">正确</text>
        </view>
        <view class="option-item"
              :class="{
                'selected': selectedAnswer === 'false',
                'disabled': showResult
              }"
              @tap="!showResult && selectAnswer('false')">
          <text class="option-label">B.</text>
          <text class="option-content">错误</text>
        </view>
      </view>

      <view v-if="showResult" class="result-section">
        <view :class="['result-message', isCorrect ? 'correct' : 'wrong']">
          {{ isCorrect ? '回答正确！' : '回答错误！' }}
        </view>
        <view class="explanation">
          <text class="explanation-title">答案解析：</text>
          <text class="explanation-content">{{ question.answerExplanation }}</text>
        </view>
      </view>

      <view class="button-group">
        <button v-if="!showResult"
                type="primary"
                @tap="submitAnswer"
                :disabled="!isAnswerSelected">
          提交答案
        </button>
        <button v-else
                type="primary"
                @tap="handleNext">
          <block v-if="isViewingRecord">返回列表</block>
          <block v-else>{{ isLastQuestion ? '完成答题' : '下一题' }}</block>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { getQuestion } from "@/api/question/question";
import { addRecord, getRecord } from "@/api/answerRecord/record";
import { getUserProfile } from "@/api/system/user"
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import { getDicts } from "@/api/system/dict/data";

const loading = ref(true)
const question = ref({
  questionTitle: '',
  questionType: '',
  questionOptions: '',
  correctAnswer: '',
  answerExplanation: ''
})
const selectedAnswer = ref('')
const selectedAnswers = ref([])
const showResult = ref(false)
const isCorrect = ref(false)
const dict = ref({
  type: {
    question_type: []
  }
})
const startTime = ref(null)
const userId = ref(null)
const questionIds = ref([])
const currentQuestionIndex = ref(-1)
const isViewingRecord = ref(false)

const isLastQuestion = computed(() => {
  if (isViewingRecord.value) {
    return true
  }
  return currentQuestionIndex.value !== -1 && currentQuestionIndex.value === questionIds.value.length - 1
})

// 解析选项
const options = computed(() => {
  const opts = question.value.questionOptions
  if (!opts) return []
  if (typeof opts === 'string') {
    try {
      return JSON.parse(opts)
    } catch (e) {
      console.error('解析选项失败:', e)
      return []
    }
  }
  if (Array.isArray(opts)) return opts
  return []
})

// 判断是否已选择答案
const isAnswerSelected = computed(() => {
  if (question.value.questionType === '2') {
    return selectedAnswers.value.length > 0
  }
  return !!selectedAnswer.value
})

function resetForNewQuestion() {
  selectedAnswer.value = ''
  selectedAnswers.value = []
  showResult.value = false
  isCorrect.value = false
  startTime.value = new Date()
}

async function loadQuestion(questionId) {
  loading.value = true;
  resetForNewQuestion();
  try {
    const res = await getQuestion(questionId);
    if (res.data) {
      question.value = res.data;
    } else {
      uni.showToast({ title: '获取题目失败', icon: 'none' });
    }
  } catch (err) {
    console.error('获取题目失败:', err);
    uni.showToast({ title: '获取题目失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

onLoad(async (options) => {
  try {
    const dictsRes = await getDicts("question_type");
    dict.value.type.question_type = dictsRes.data;

    const userRes = await getUserProfile();
    userId.value = Number(userRes.data.userId);

    isViewingRecord.value = !!options.recordId;

    if (isViewingRecord.value) {
      loading.value = true;
      const recordId = Number(options.recordId);
      const recordRes = await getRecord(recordId);

      if (recordRes.code === 200 && recordRes.data) {
        const recordData = recordRes.data;
        let userAnswer = recordData.userAnswer;
        if (typeof userAnswer === 'string') {
          try { userAnswer = JSON.parse(userAnswer); } catch (e) { userAnswer = []; }
        }
        
        const qRes = await getQuestion(recordData.questionId);
        if (qRes.data) {
          question.value = qRes.data;
          if (question.value.questionType === '2') {
            selectedAnswers.value = userAnswer;
          } else if (question.value.questionType === '3') {
            selectedAnswer.value = userAnswer[0] === 'A' ? 'true' : 'false';
          } else {
            selectedAnswer.value = userAnswer[0];
          }
          showResult.value = true;
          isCorrect.value = recordData.isCorrect === 1;
        } else {
          uni.showToast({ title: '获取题目失败', icon: 'none' });
        }
      } else {
        uni.showToast({ title: '获取答题记录失败', icon: 'none' });
      }
    } else if (options.id && options.ids) {
      const questionIdStr = options.id;
      
      try {
        questionIds.value = JSON.parse(options.ids);
      } catch (e) {
        console.error("解析题目ID列表失败:", e);
        questionIds.value = [];
      }
      
      currentQuestionIndex.value = questionIds.value.findIndex(id => id == questionIdStr);
      
      if (currentQuestionIndex.value === -1) {
        uni.showToast({ title: '无效的题目序列', icon: 'none' });
        loading.value = false;
        return;
      }
      
      await loadQuestion(Number(questionIdStr));
    } else {
      uni.showToast({ title: '题目ID或序列缺失', icon: 'none' });
    }
  } catch (err) {
    console.error("加载页面失败:", err);
    uni.showToast({ title: '页面加载失败', icon: 'none' });
  } finally {
    if(loading.value) loading.value = false;
  }
});

// 单选题选择答案
function selectAnswer(answer) {
  selectedAnswer.value = answer
}

// 多选题选择答案
function selectMultiAnswer(answer) {
  const index = selectedAnswers.value.indexOf(answer)
  if (index > -1) {
    selectedAnswers.value.splice(index, 1)
  } else {
    selectedAnswers.value.push(answer)
  }
}

// 提交答案
function submitAnswer() {
  try {
    const correctAnswer = JSON.parse(question.value.correctAnswer)
    const endTime = new Date()
    const timeSpent = Math.floor((endTime - startTime.value) / 1000)

    let isAnswerCorrect = false
    if (question.value.questionType === '2') {
      // 多选题答案比较
      const userAnswer = [...selectedAnswers.value].sort()
      const correctAnswerSorted = [...correctAnswer].sort()
      isAnswerCorrect = userAnswer.length === correctAnswerSorted.length &&
        userAnswer.every((answer, index) => answer === correctAnswerSorted[index])
    } else if (question.value.questionType === '1') {
      // 单选题答案比较
      isAnswerCorrect = correctAnswer.includes(selectedAnswer.value)
    } else if (question.value.questionType === '3') {
      // 判断题答案比较
      const isTrue = correctAnswer[0] === 'A'
      const userIsTrue = selectedAnswer.value === 'true'
      isAnswerCorrect = isTrue === userIsTrue
    }
    showResult.value = true
    isCorrect.value = isAnswerCorrect

    // 添加答题记录
    const recordData = {
      userId: userId.value,
      questionId: question.value.id,
      circleId: question.value.circleId,
      articleId: question.value.articleId,
      userAnswer: question.value.questionType === '2' ?
        JSON.stringify(selectedAnswers.value.sort()) : // 多选题答案排序
        question.value.questionType === '3' ?
          JSON.stringify([selectedAnswer.value === 'true' ? 'A' : 'B']) : // 判断题答案
          JSON.stringify([selectedAnswer.value]), // 单选题答案
      isCorrect: isAnswerCorrect ? 1 : 0,
      pointsEarned: isAnswerCorrect ? question.value.rewardPoints : 0,
      answerTime: endTime.toISOString(),
      timeSpent: timeSpent
    }

    addRecord(recordData).then(res => {
      if (res.code === 200) {
        // 答题记录添加成功
      }
    }).catch(err => {
      console.error('答题记录添加失败:', err)
    })
  } catch (e) {
    console.error('解析正确答案失败:', e)
    uni.showToast({
      title: '答案格式错误',
      icon: 'none'
    })
  }
}

// 返回列表或下一题
function handleNext() {
  if (isLastQuestion.value) {
    uni.navigateBack()
    return
  }
  
  currentQuestionIndex.value++;
  const nextQuestionId = questionIds.value[currentQuestionIndex.value];
  if (nextQuestionId) {
    loadQuestion(Number(nextQuestionId));
  }
}

// 获取题目类型标签
function getQuestionTypeLabel(type) {
  const typeDict = dict.value.type.question_type.find(item => item.dictValue === type)
  return typeDict ? typeDict.dictLabel : type
}
</script>

<style>
.answer-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.loading {
  text-align: center;
  padding: 30px;
  color: #999;
}

.question-container {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.question-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.question-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  display: block;
  color: #333;
  line-height: 1.6;
}

.question-type {
  color: #1890ff;
  font-weight: bold;
  margin-left: 12px;
  font-size: 14px;
}

.options-list {
  margin: 20px 0;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 15px;
  margin-bottom: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background-color: #fff;
  transition: all 0.3s ease;
}

.option-item.selected {
  background-color: #f0f7ff;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.option-item.disabled {
  opacity: 0.7;
  cursor: not-allowed;
  pointer-events: none;
}

.option-item.disabled.selected {
  background-color: #f0f7ff;
  border-color: #1890ff;
}

.option-label {
  font-weight: bold;
  margin-right: 12px;
  color: #1890ff;
  min-width: 24px;
}

.option-content {
  flex: 1;
  color: #333;
  line-height: 1.5;
}

.result-section {
  margin-top: 24px;
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.result-message {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  text-align: center;
}

.result-message.correct {
  color: #1890ff;
}

.result-message.wrong {
  color: #ff4d4f;
}

.explanation {
  margin-top: 16px;
  padding: 16px;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #f0f0f0;
}

.explanation-title {
  font-weight: bold;
  margin-bottom: 8px;
  display: block;
  color: #333;
}

.explanation-content {
  color: #666;
  line-height: 1.6;
}

.button-group {
  margin-top: 32px;
  padding: 0 15px;
}

button[type="primary"] {
  background-color: #1890ff !important;
  border-color: #1890ff !important;
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  border-radius: 22px;
}

button[type="primary"][disabled] {
  background-color: #bfbfbf !important;
  border-color: #bfbfbf !important;
  color: #fff !important;
}
</style>
